<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\web\ForbiddenHttpException;
use backend\models\ActionModel;

/**
 * Base controller
 *
 * @property \yii\web\Request $request The request component.
 * @property \yii\web\Response $response The response component.
 */
abstract class BaseController1 extends \common\components\BaseController
{
	const MSG_NORMAL = 0;
	const MSG_SUCCESS = 1;
	const MSG_ERROR = 2;
	const MAX_FENYE_PAGE = 100000;
	const CACHE_TIME = 3600;

	// 是否验证本系统的权限逻辑
	public $verifyPermission = true;

	public function beforeAction($action)
	{
		//如果未登录，则直接返回
		if(Yii::$app->user->isGuest){
			return $this->redirect(['site/login']);
			return $this->goHome();
		}
		//获取路径
		//$path = Yii::$app->request->pathInfo;

		//忽略列表
		/*if (in_array($path, $this->ignoreList)) {
			return true;
		}

		if (Yii::$app->user->can($path)) {
			return true;
		} else {
			throw new ForbiddenHttpException(Yii::t('app', 'message 401'));
		}*/
	}
	/*public function beforeAction($action)
	{
        set_time_limit(60);//响应时间改为60秒

		if (parent::beforeAction($action)) {

			//非线上环境强制 填写方法名称
            if (YII_ENV_DEV) {
                $permissionArr = Yii::$app->params['permissionControllers'];
                list($controllerId, $actionId) = explode('/', $this->getRoute());
                $className = str_replace(' ', '', ucwords(str_replace('-', ' ', $controllerId)));
                $controName = $className . "Controller";
                if (array_key_exists($controName, $permissionArr)) {
                    $actionName = str_replace(' ', '', ucwords(str_replace('-', ' ', $actionId)));
                    $class = "backend\\controllers\\" . $controName;
                    $action = "action" . $actionName;
                    $rf = new \ReflectionClass($class);
                    $method = $rf->getMethod($action);
                    $actionModel = new ActionModel($method);
                    $title = $actionModel->getTitle();
                    $name = $actionModel->getName();
                    if (empty($title) || ($title == $name)) {
                        throw new ForbiddenHttpException('抱歉，此控制器：'.$controName.'，此方法：'.$method->name.', 没有添加注释请添加！如： @name 测试。');
                    }
                }
            }

			if (Yii::$app->request->get('frames')) {
				$this->goHome();
				$this->redirect(['main/index', 'action' => $this->getRoute()]);
				return false;
			}

			if ($this->verifyPermission) {
				// 验证登录
				if (Yii::$app->user->getIsGuest()) {
					return $this->redirect(['main/login']);
				}
				// 验证权限
//				if (!Yii::$app->user->identity->getIsSuperAdmin()) {
//					$permissions = $this->getUserPermissions();
//				    if (!in_array($this->getRoute(), $permissions)) {
//                        throw new ForbiddenHttpException('您所属的管理员角色无此权限');
//                    }
//				}
			}

			return true;
		} else {
			return false;
		}
	}
*/
	protected function getUserPermissions(){
	    $permissions = Yii::$app->getSession()->get('permissions');
	    if (!$permissions) {
	        $role = Yii::$app->user->identity->role;
	        $roleModel = AdminUserRole::find()->andWhere("name in('".implode("','",explode(',',$role))."')")->all();
	        if($roleModel){
	            $arr = array();
	            foreach ($roleModel as $val) {
	                if($val->permissions)
	                    $arr = array_unique(array_merge($arr,json_decode($val->permissions)));
	            }
	            Yii::$app->getSession()->set('permissions', json_encode($arr));
	            $permissions = json_decode($permissions, true);
	        }
	    }else{
	        $permissions = json_decode($permissions, true);
	    }
	    return $permissions ? $permissions : [];
	}
	
	/**
	 * 获得请求对象
	 */
	public function getRequest()
	{
		return \Yii::$app->getRequest();
	}

	/**
	 * 获得返回对象
	 */
	public function getResponse()
	{
		return \Yii::$app->getResponse();
	}

	/**
	 * 跳转到提示页面
	 * @param string $message	提示语
	 * @param int $msgType		提示类型，不同提示类型提示语样式不一样
	 * @param string $url		自动跳转url地址，不设置则默认显示返回上一页连接
	 * @return string
	 */
	public function redirectMessage($message, $msgType = self::MSG_NORMAL, $url = '')
	{
		switch ($msgType) {
			case self::MSG_SUCCESS: $messageClassName = 'infotitle2';break;
			case self::MSG_ERROR: $messageClassName = 'infotitle3';break;
			default: $messageClassName = 'marginbot normal';break;
		}
		return $this->render('/message', array(
			'message' => $message,
			'messageClassName' => $messageClassName,
			'url' => $url,
		));
	}
	
	protected function _setcsvHeader($filename){
	    $now = gmdate("D, d M Y H:i:s");
	    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
	    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
	    header("Last-Modified: {$now} GMT");
	    // force download
	    header("Content-Type: application/force-download");
	    header("Content-Type: application/octet-stream");
	    header("Content-Type: application/download");
	    header("Content-type: application/vnd.ms-excel; charset=utf8");
	    // disposition / encoding on response body
	    header("Content-Disposition: attachment;filename={$filename}");
	    header("Content-Transfer-Encoding: binary");
	    //设置utf-8 + bom ，处理汉字显示的乱码
	    print(chr(0xEF).chr(0xBB).chr(0xBF));
	}
	protected function _array2csv(array &$array){
	    if (count($array) == 0) {
	        return  null;
	    }
	    set_time_limit(0);//响应时间改为60秒
	    ini_set('memory_limit', '512M'); 
	    ob_start();
	    $df = fopen("php://output", 'w');
	    fputcsv($df, array_keys(reset($array)));
	    foreach ($array as $row) {
	        fputcsv($df, $row);
	    }
	    fclose($df);
	    return ob_get_clean();
	}
}